package com.business.business.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.business.business.common.base.BaseService;
import com.business.business.model.Business;
import com.business.business.model.EmgProfessor;
import com.business.business.model.EmgTeam;
import com.business.business.support.model.RespEntity;
import com.business.business.support.utils.https.StringUtil;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.BusinessMapper;
import com.business.business.web.mapper.EmgProfessorMapper;
import com.business.business.web.mapper.EmgTeamMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author xulumin
* @description 针对表【emg_team(应急队伍表)】的数据库操作Service
* @createDate 2024-03-20 15:30:02
*/
@Service
public class EmgTeamService extends BaseService {


    @Resource
    private EmgTeamMapper emgTeamMapper;

    @Resource
    private BusinessMapper businessMapper;

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 应急队伍信息新增或更新
     */
    public RespEntity addOrUpdateTeam(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取bean
        EmgTeam emgTeam = jsonObject.toBean(EmgTeam.class);

        // 判断必填字段
            if (StringUtil.strIsNullOrEmpty(emgTeam.getName()) || "null".equals(String.valueOf(emgTeam.getNumber()))) {
            return RespEntity.fail("请填写队伍名称和队伍人数");
        }
        String principal = emgTeam.getPrincipal();

        if (StringUtil.strIsNullOrEmpty(emgTeam.getBusinessId()) || StringUtil.strIsNullOrEmpty(emgTeam.getPrincipal())) {
            return RespEntity.fail("请填写队伍负责人和所属单位");
        }

        int result = -1;
        // 判断是否新增或更新
        if (StringUtil.strIsNullOrEmpty(emgTeam.getId())) {
            // 为空，新增
            emgTeam.setId(UUID.randomUUID().toString());
            result = emgTeamMapper.insert(emgTeam);
        } else {
            result = emgTeamMapper.updateById(emgTeam);
        }
        // 判断数据库是否操作成功
        if (result > 0) {
            return RespEntity.success();
        } else {
            return RespEntity.fail("操作失败！");
        }
    }

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 获取应急队伍信息列表
     */
    public RespEntity getTeamList(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 判断页码和页面大小
        Integer page = jsonObject.getInt("page");
        Integer limit = jsonObject.getInt("limit");

        page = "null".equals(String.valueOf(page)) ? 1 : page;
        limit = "null".equals(String.valueOf(limit)) ? 5 : limit;

        String areaId = jsonObject.getStr("areaId");
        String businessId = jsonObject.getStr("businessId");
        Page<EmgTeam> pageInfo = new Page<>(page, limit);
        if (StringUtil.strIsNullOrEmpty(areaId) && !StringUtil.strIsNullOrEmpty(businessId)) {
            // 区域Id为空，按企业查
            // 构建查询条件
            LambdaQueryWrapper<EmgTeam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(jsonObject.containsKey("name"), EmgTeam::getName, jsonObject.getStr("name"))
                    .eq(jsonObject.containsKey("businessId"), EmgTeam::getBusinessId, jsonObject.getStr("businessId"));
            IPage<EmgTeam> iPage = emgTeamMapper.selectPage(pageInfo, lambdaQueryWrapper);
            return RespEntity.success(iPage);
        } else if (StringUtil.strIsNullOrEmpty(businessId) && !StringUtil.strIsNullOrEmpty(areaId)) {
            // 企业Id为空，按照区域查
            // 查询该区域下企业
            LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(Business::getArea, areaId).select(Business::getId);
            List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
            List<String> ids = new ArrayList<>();
            for (Business business : businesses) {
                ids.add(business.getId());
            }
            // 构建查询条件
            LambdaQueryWrapper<EmgTeam> lambdaQuery = new LambdaQueryWrapper<>();
            lambdaQuery.like(jsonObject.containsKey("name"), EmgTeam::getName, jsonObject.getStr("name"))
                    .in(EmgTeam::getBusinessId, ids);
//            IPage<EmgTeam> iPage = emgTeamMapper.selectPage(pageInfo, lambdaQuery);
            List<EmgTeam> emgTeams = emgTeamMapper.selectList(lambdaQuery);
            return RespEntity.success(emgTeams);
        } else {
            // 企业ID和区域ID都为空 全查
            LambdaQueryWrapper<EmgTeam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(jsonObject.containsKey("name"), EmgTeam::getName, jsonObject.getStr("name"))
                    .eq(jsonObject.containsKey("businessId"), EmgTeam::getBusinessId, jsonObject.getStr("businessId"));
            IPage<EmgTeam> iPage = emgTeamMapper.selectPage(pageInfo, lambdaQueryWrapper);
            return RespEntity.success(iPage);
        }

    }


    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 应急队伍删除
     */
    public RespEntity delTeam(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取要删除的物资id
        String ids = jsonObject.getStr("id");
        String[] split = ids.split(",");
        int result = emgTeamMapper.deleteBatchIds(Arrays.asList(split));
        if (result == split.length) {
            return RespEntity.success("删除成功");
        } else {
            return RespEntity.fail("删除失败");
        }
    }

    /**
     * Author: xulumin
     * Date: 2024/3/20
     * Description: 获取应急队伍信息
     */
    public RespEntity getTeamInfo(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取id
        String id = jsonObject.getStr("id");
        if (StringUtil.strIsNullOrEmpty(id)) {
            return RespEntity.fail("请填写要查询的id");
        }
        EmgTeam emgTeam = emgTeamMapper.selectById(id);
        if (emgTeam != null) {
            return RespEntity.success(emgTeam);
        } else {
            return RespEntity.fail("查询失败");
        }

    }

}
